package com.tjjingpan.broadcastbestpractice.LearnKotlin

//高阶函数
fun num1AndNum2(num1:Int,num2:Int,operation:(Int,Int)-> Int):Int{
    val result = operation(num1,num2)
    return result
}

fun plus(num1:Int,num2:Int):Int{
    return num1 + num2
}
fun minus(num1:Int,num2:Int):Int{
    return num1 - num2
}

//StringBuilder类定义了一个build扩展函数
fun StringBuilder.build(block:StringBuilder.() ->Unit):StringBuilder{
    block()
    return this
}


inline fun printString(str:String,block:(String) ->Unit){
    println("printString Begin")
    block(str)
    println("printString End")
}
fun main(){
    val num1 = 100
    val num2 = 80
    val result1 = num1AndNum2(num1,num2,::plus)
    val result2 = num1AndNum2(num1,num2,::minus)
    println("result1 is $result1")
    println("result2 is $result2")

    val result3 = num1AndNum2(num1,num2){n1,n2 ->
        n1 + n2
    }
    val result4 = num1AndNum2(num1,num2){n1,n2 ->
        n1 - n2
    }
    println("result1 is $result3")
    println("result2 is $result4")

    val list = listOf("Apple","Banana","Orange","Pear","Grage")
    val result = StringBuilder().build {
        append("Strat eating fruits.\n")
        for(fruit in list){
            append(fruit).append("\n")
        }
        append("Eat all fruits")
    }
    println(result.toString())

    println("main start")
    val str =""
    printString(str){ s ->
        println("lambda start")
        if(s.isEmpty()) return
        println(s)
        println("lambda end")
    }
    println("main end")
}